import dashscope
import os
from http import HTTPStatus
import json
import requests
import time
import random
from typing import Optional, Dict, Any
from datetime import datetime

class SpeechToTextProcessor:
    """
    语音转文字处理工具类
    封装阿里云达摩院语音转文字API调用
    
    使用示例:
        # 方式1: 从环境变量读取API Key
        processor = SpeechToTextProcessor()
        
        # 方式2: 直接传入API Key
        processor = SpeechToTextProcessor(api_key="your-api-key")
    """
    
    def __init__(self, model: str = 'paraformer-v2', api_key: Optional[str] = None):
        """
        初始化语音转文字处理器
        
        参数:
            model: 使用的语音识别模型，默认为'paraformer-v2'
            api_key: 可选的API密钥，未提供时从环境变量DASHSCOPE_API_KEY读取
        """
        self.model = model
        self._init_api_key(api_key)
    
    def _init_api_key(self, api_key: Optional[str]):
        """
        初始化API密钥
        
        参数:
            api_key: 可选的API密钥
        """
        if api_key:
            dashscope.api_key = api_key
        else:
            dashscope.api_key = os.getenv('DASHSCOPE_API_KEY')
        
        if not dashscope.api_key:
            raise ValueError("未设置DashScope API密钥，请通过参数传入或设置环境变量DASHSCOPE_API_KEY")


    def get_json_file(self, url):
        """
            Downloads a file from a given URL to a local path.

            Parameters:
            - url: File URL Address
            - local_path: Local Path where the file will be saved

            Returns:
            None
        """
        try:
            response = requests.get(url, stream=True, timeout=10)
            response.raise_for_status()
        except requests.RequestException as e:
            time.sleep(random.randint(1, 5))
            response = requests.get(url,
                                    stream=True,
                                    allow_redirects=True,
                                    timeout=15)
            print(f'Failed to download the file: {e} ,retrying!')

        return response.json()
            
    def transcribe(self, file_url: str) -> Optional[str]:
        """
        提交语音转文字任务并获取结果
        
        参数:
            file_url: 音频文件的公网可访问URL
            
        返回:
            dict: 转写结果字典，包含转写文本等信息
            None: 转写失败时返回None
        """
        try:
            # 提交转写任务
            task_response = dashscope.audio.asr.Transcription.async_call(
                model=self.model, 
                file_urls=[file_url]
            )
            
            if not task_response or not task_response.output or not task_response.output.task_id:
                print("提交转写任务失败")
                return None
                
            # 获取转写结果
            transcribe_response = dashscope.audio.asr.Transcription.wait(
                task=task_response.output.task_id
            )
            
            if transcribe_response.status_code == HTTPStatus.OK:
                print(f"[{datetime.now()}] 转写成功")
            else:
                print(f"转写失败，状态码: {transcribe_response.status_code}")
                return None
            
            if transcribe_response.output.task_status == 'SUCCEEDED':
                transcription_result = transcribe_response.output.get('results')
                if transcription_result:
                    transcription_url = json.loads(
                        json.dumps(transcription_result))[0]['transcription_url']
                    print('get transcription_url: ', transcription_url)
                    if transcription_url:
                        # download the transcription result
                        trans_result = self.get_json_file(transcription_url)
                        return trans_result['transcripts'][0]['text']
                    else:
                        print("未获取到 transcription_url")
                        return None
                else:
                    print("未获取到 transcription_result")
                    return None
            else:
                print(f"转写任务未完成，当前状态: {transcribe_response.output.task_status}")
                return None
                                    
        except Exception as e:
            print(f"转写过程中发生异常: {str(e)}")
            return None

    @staticmethod
    def print_result(result: Dict[str, Any]) -> None:
        """
        格式化打印转写结果
        
        参数:
            result: 转写结果字典
        """
        if not result:
            print("无有效转写结果")
            return
            
        print("转写结果:")
        print(json.dumps(result, indent=4, ensure_ascii=False))
        if 'transcription_url' in result:
            print(f"转写结果文件URL: {result['transcription_url']}")